package com.xiaowu.netmusic.controller;

import com.xiaowu.netmusic.common.exception.OAuth2Exception;
import com.xiaowu.netmusic.domain.po.UserPO;
import com.xiaowu.netmusic.service.UserService;
import com.xiaowu.netmusic.service.impl.GithubOAuth2Service;
import com.xiaowu.netmusic.utils.JwtUtil;
import com.xiaowu.netmusic.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/oauth2")
@RequiredArgsConstructor
@Tag(name = "第三方用户登录操作接口", description = "第三方用户登录操作")
public class GithubUserController {

    private final GithubOAuth2Service githubOAuth2Service;

    private  final UserService userService;


    @Operation(summary = "GitHub第三方登录接口")
    @PostMapping("/github")
    public Result<Object> githubLogin(@RequestBody Map<String, String> payload) {
        String code = payload.get("code");

        try {
            String accessToken = githubOAuth2Service.getAccessToken(code);
            Map<String, Object> userInfo = githubOAuth2Service.getUserInfo(accessToken);

            // ====根据GitHub userId 查自己数据库 ===
            String githubId = userInfo.get("id").toString(); // GitHub ID，唯一
            UserPO user = userService.findByGithubId(githubId);

            if (user == null) {
                // ===没有就注册一个新用户
                user = new UserPO();
                user.setGithubId(githubId);
                user.setUsername(userInfo.get("login").toString());
                user.setAvatar(userInfo.get("avatar_url").toString());
                userService.insertUserByGithub(user);
            }

            // 生成自己的JWT Token ===
            String jwtToken = JwtUtil.generateToken(user.getId(),user.getUsername());

            // 返回自己的 token
            Map<String, Object> data = new HashMap<>();
            data.put("token", jwtToken);

            return Result.success(data);

        } catch (OAuth2Exception e) {
            return Result.error(e.getMessage());
        }
    }



    private Map<String, Object> filterUserInfo(Map<String, Object> userInfo) {
        if (userInfo == null) {
            return Map.of("error", "No user information received");
        }

        Map<String, Object> filtered = new LinkedHashMap<>();

        // 确保必需字段存在
        if (userInfo.containsKey("id")) {
            filtered.put("id", userInfo.get("id"));
        }
        if (userInfo.containsKey("login")) {
            filtered.put("login", userInfo.get("login"));
        }

        // 处理可选字段
        filtered.put("name", userInfo.getOrDefault("name", ""));
        filtered.put("avatar_url", userInfo.getOrDefault("avatar_url", ""));
        filtered.put("email", userInfo.getOrDefault("email", ""));

        return filtered;
    }
}
